<template>
  <div class="w-full">
    <component :is="stemType" />
    <div class="mt-20px" v-for="(i, i_index) in sqs" :key="i_index">
      <Stem
        :master="master"
        :data="i"
        :answer="answer"
        :answerIndex="i_index"
        :student-answer="studentAnswer"
        :readonly="readonly"
        @change-student-answer="
          (e) => {
            $emit('change-student-answer', e)
          }
        "
      />
    </div>
  </div>
</template>

<script>
import Default from './components/default'
import SingleChoice from './components/single-choice'
import MultipleChoice from './components/multiple-choice'

export default {
  name: 'Stem',
  components: {
    Default,
    SingleChoice,
    MultipleChoice
  },
  provide() {
    return {
      emit: this.$emit.bind(this),
      props: this.$props
    }
  },
  props: {
    master: {
      type: String,
      default: ''
    },
    index: {
      type: Number,
      default: -1
    },
    data: {
      type: [Object, String],
      default: () => {}
    },
    answer: {
      type: Object,
      default: () => {}
    },
    answerIndex: {
      type: Number,
      default: 0
    },
    studentAnswer: {
      type: [Object, String],
      default: () => {}
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {}
  },
  computed: {
    stemType() {
      const { data: stem, answer, answerIndex } = this

      try {
        return this.getStemType({
          stem,
          answer: answer.anSqs[answerIndex].ans[0].anStudent
            .replace(/<[\w\W]*?>/gi, '') // 清空html标签
            .trim() // 清空首尾空格
            .replace('&nbsp;', '') // 清空空格标记
        })
      } catch (error) {
        return this.getStemType({ stem, answer })
      }
    },
    sqs() {
      const { data: stem } = this
      const { sqs = [] } = stem

      return sqs
    }
  },
  mounted() {},
  methods: {
    getStemType(params) {
      const { stem, answer } = params

      const { type } = stem

      if (!answer || typeof answer != 'string' || !['选择题'].includes(type)) {
        return 'Default'
      }

      if (answer.split('').length > 1) {
        return 'MultipleChoice'
      } else {
        return 'SingleChoice'
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
